<?php
class ArticleCateModel extends CommonModel {
	protected $_validate = array (
		array (
			'name',
			'require',
			'名称必须' 
			) 
		);
	/**
	 * 生成树型结构所需要的2维数组
	 * 
	 * @var array
	 */
	var $tree = array ();
	
	/**
	 * 获取树状分类数组
	 *
	 * @return array
	 * @author
	 *
	 *
	 */
	function getTree() {
		$this->tree = array ();
		$this->tree =$this->getGrandFather();
		$children = array();

		if (is_array ( $this->tree )) {
			foreach ( $this->tree as $key => $value ) {
				if($this->hasChildren($value['id'])){
					$this->tree[$key]['child'] =  array_map ( array ($this,'getChildren' ), array ($value ['id'] ) );
				}
			}
		}
		// print_r($this->tree);
		return $this->tree;
	}

	public function getGrandFather(){
		return $this->where ( 'pid = 0' )->order ( 'id desc' )->select ();
	}

	public function hasChildren($id){
		if ($this->where ( array ('pid' => $id ) )->count () > 0) { // 检查是否还有子级
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 获取所有子分类
	 * 适合递归
	 * 
	 * @param int $pid        	
	 * @return array
	 */
	public function getChildren($pid) {

		$currentChildren = array();

		$currentChildren = $this->where(array('pid' => $pid ))->select();	//当前层级

		if(is_array($currentChildren)){
			foreach($currentChildren as $key=>$value){
				$child = array_map ( array ($this,__FUNCTION__), array ($value['id']));
				if($child['0'] != null)
					$currentChildren[$key]['child'] = $child;
			}
			return $currentChildren;
		}else{
			return null;
		}
	}
}